class Article < ActiveRecord::Base
  belongs_to :category
  
  validates_presence_of :name, :description, :image_url, :category_id
  validates_numericality_of :price
  validate :price_must_be_at_least_a_cent
  validates_uniqueness_of :name, :case_sensitive => false
  
  def self.find_articles_for_sale
    Article.find(:all, :order => "name")
  end
  
  def self.search(query = nil)
    Article.find(:all, :conditions => (query.nil? ? [] : ["name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%"]))
  end
  
  protected 
  def price_must_be_at_least_a_cent
    errors.add(:price, 'should be at least 0.01') if price.nil? || price < 0.01
  end
  
end


# == Schema Information
#
# Table name: articles
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  description :text
#  price       :decimal(8, 2)   default(0.0)
#  created_at  :datetime
#  updated_at  :datetime
#  image_url   :string(255)
#  category_id :integer
#

